<template>
  <div class="document-detail-container">
    <!-- 顶部操作栏 -->
    <div class="top-actions">
      <div class="left-actions">
        <van-icon name="arrow-left" size="24" @click="goBack" />
      </div>
      <div class="right-actions">
        <van-icon name="more-o" size="24" @click="showMoreMenu = true" />
      </div>
    </div>

    <!-- 文档头部信息 -->
    <div class="document-header">
      <input
        v-model="document.doc_title"
        class="document-title"
        :readonly="!canEdit"
        @blur="updateTitle"
        placeholder="请输入文档标题"
      />
      <div class="document-meta">
        <span class="document-type">{{ getDocumentTypeName(document.doc_type) }}</span>
        <span class="document-time">最后编辑: {{ formatTime(document.updateTime) }}</span>
        <span class="document-version">v{{ document.version }}</span>
        <span v-if="document.team_id !== 0" class="document-team">所属团队</span>
      </div>
    </div>

    <!-- 编辑器工具栏 -->
    <div v-if="canEdit" class="editor-toolbar">
      <div class="tool-group">
        <van-icon name="font" size="18" @click="formatText('formatBlock', 'h1')" title="标题" />
        <van-icon name="font-o" size="18" @click="formatText('formatBlock', 'p')" title="正文" />
        <van-icon name="bold" size="18" @click="formatText('bold')" title="加粗" />
        <van-icon name="italic" size="18" @click="formatText('italic')" title="斜体" />
        <van-icon name="underline" size="18" @click="formatText('underline')" title="下划线" />
        <van-icon name="strikethrough" size="18" @click="formatText('strikeThrough')" title="删除线" />
      </div>
      <div class="tool-group">
        <van-icon name="list-o" size="18" @click="formatText('insertUnorderedList')" title="无序列表" />
        <van-icon name="ordered-list" size="18" @click="formatText('insertOrderedList')" title="有序列表" />
        <van-icon name="align-left" size="18" @click="formatText('justifyLeft')" title="左对齐" />
        <van-icon name="align-center" size="18" @click="formatText('justifyCenter')" title="居中" />
        <van-icon name="align-right" size="18" @click="formatText('justifyRight')" title="右对齐" />
      </div>
      <div class="tool-group">
        <van-icon name="edit" size="18" @click="toggleEdit()" title="编辑/预览" />
      </div>
    </div>

    <!-- 文档内容区域 -->
    <div v-if="!loading" class="document-content-container">
      <!-- 编辑模式 -->
      <div v-if="isEditing && canEdit" class="editor-container">
        <div
          ref="editorRef"
          class="rich-editor"
          contenteditable
          @input="handleContentChange"
          @focus="editorFocused = true"
          @blur="editorFocused = false"
        ></div>
      </div>
      <!-- 预览模式 -->
      <div v-else class="preview-container" v-html="document.doc_content || '<p>暂无内容</p>'"></div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-actions">
      <div class="left-buttons">
        <van-button
          v-if="canEdit"
          type="default"
          size="small"
          @click="toggleEdit()"
          :text="isEditing ? '取消' : '编辑'"
        />
      </div>
      <div class="right-buttons">
        <van-button
          v-if="canEdit && isEditing"
          type="primary"
          size="small"
          :loading="saving"
          @click="saveDocument"
        >
          保存
        </van-button>
        <van-button
          type="default"
          size="small"
          @click="showVersions = true"
        >
          历史版本
        </van-button>
      </div>
    </div>

    <!-- 更多操作菜单 -->
    <van-action-sheet v-model:show="showMoreMenu" :actions="moreActions" @select="handleMoreAction" />

    <!-- 版本历史弹窗 -->
    <van-popup v-model:show="showVersions" position="right" round :width="300">
      <div class="version-panel">
        <div class="panel-header">
          <h3>版本历史</h3>
          <van-icon name="cross" size="20" @click="showVersions = false" />
        </div>
        <div class="version-list">
          <div
            v-for="version in documentVersions"
            :key="version.id"
            class="version-item"
            @click="selectVersion(version)"
          >
            <div class="version-info">
              <div class="version-header">
                <span class="version-number">v{{ version.version }}</span>
                <span v-if="version.version === document.version" class="current-version">当前版本</span>
              </div>
              <div class="version-meta">
                <span class="version-editor">{{ version.editor?.username || '未知用户' }}</span>
                <span class="version-time">{{ formatTime(version.edit_time) }}</span>
              </div>
              <div class="version-note" v-if="version.edit_note">{{ version.edit_note }}</div>
            </div>
            <van-icon name="arrow" size="20" />
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 版本详情弹窗 -->
    <van-popup v-model:show="showVersionDetail" position="center" round :width="90%">
      <div class="version-detail-panel">
        <div class="panel-header">
          <h3>版本 v{{ selectedVersion?.version }}</h3>
          <van-icon name="cross" size="20" @click="showVersionDetail = false" />
        </div>
        <div class="version-detail-info">
          <p>编辑者: {{ selectedVersion?.editor?.username || '未知用户' }}</p>
          <p>编辑时间: {{ selectedVersion?.edit_time }}</p>
          <p v-if="selectedVersion?.edit_note">编辑备注: {{ selectedVersion.edit_note }}</p>
        </div>
        <div class="version-detail-content" v-html="selectedVersion?.doc_content || '<p>暂无内容</p>'"></div>
        <div class="panel-footer">
          <van-button type="default" @click="showVersionDetail = false">关闭</van-button>
          <van-button 
            type="primary" 
            @click="restoreVersion"
            :disabled="selectedVersion?.version === document.version"
          >
            恢复此版本
          </van-button>
        </div>
      </div>
    </van-popup>

    <!-- 编辑备注弹窗 -->
    <van-popup v-model:show="showEditNote" position="bottom" round>
      <div class="edit-note-panel">
        <div class="panel-header">
          <h3>编辑备注</h3>
          <van-icon name="cross" size="20" @click="showEditNote = false" />
        </div>
        <div class="note-input">
          <textarea
            v-model="editNote"
            rows="3"
            placeholder="请输入本次修改的内容摘要（选填）"
            maxlength="512"
          ></textarea>
          <div class="note-count">{{ editNote.length }}/512</div>
        </div>
        <div class="panel-footer">
          <van-button type="default" @click="showEditNote = false">取消</van-button>
          <van-button type="primary" @click="confirmSaveWithNote">确认</van-button>
        </div>
      </div>
    </van-popup>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <van-loading type="spinner" color="#1989fa" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showToast } from 'vant';
import { documentStore } from '../stores/document/document';
import { userStore } from '../stores/user/user';
import type { Document, DocumentVersion } from '../models/document';

const route = useRoute();
const router = useRouter();
const docStore = documentStore();
const userStoreAPI = userStore();

// 获取文档ID
const docId = computed(() => Number(route.params.id) || 0);

// 响应式数据
const document = reactive<Document>({
  id: 0,
  doc_title: '',
  doc_type: 1,
  team_id: 0,
  creator_uid: 0,
  doc_content: '',
  version: 1,
  last_editor_uid: 0,
  edit_status: 0,
  permission: 2,
  createTime: new Date().toISOString(),
  updateTime: new Date().toISOString(),
  isDelete: 0
});

const loading = ref(true);
const isEditing = ref(false);
const saving = ref(false);
const showMoreMenu = ref(false);
const showVersions = ref(false);
const showVersionDetail = ref(false);
const showEditNote = ref(false);
const editorRef = ref<HTMLElement>();
const editorFocused = ref(false);
const editNote = ref('');
const selectedVersion = ref<DocumentVersion>();
const documentVersions = ref<DocumentVersion[]>([]);

// 当前用户ID
const currentUserId = computed(() => userStoreAPI.getCurrentUser()?.id || 0);

// 是否可编辑
const canEdit = computed(() => {
  // 个人文档或有编辑权限
  return document.permission >= 2 || document.creator_uid === currentUserId.value;
});

// 更多操作菜单
const moreActions = computed(() => {
  const actions = [];
  
  if (document.team_id !== 0) {
    actions.push({
      name: '修改权限',
      value: 'permission'
    });
  }
  
  if (currentUserId.value === document.creator_uid) {
    actions.push({
      name: '删除文档',
      value: 'delete',
      color: '#ee0a24'
    });
  }
  
  return actions;
});

// 辅助函数
const getDocumentTypeName = (type: number) => {
  return docStore.getDocumentTypeName(type);
};

const formatTime = (timeStr: string) => {
  const date = new Date(timeStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 方法
const loadDocument = async () => {
  if (!docId.value) {
    showToast('文档ID无效');
    router.push('/document/manage');
    return;
  }
  
  loading.value = true;
  try {
    // 获取文档详情
    const docData = await docStore.fetchDocumentDetail(docId.value);
    if (docData) {
      Object.assign(document, docData);
      
      // 加载版本历史
      await loadVersions();
      
      // 初始化编辑器内容
      await nextTick();
      if (editorRef.value && document.doc_content) {
        editorRef.value.innerHTML = document.doc_content;
      }
    } else {
      showToast('文档不存在');
      router.push('/document/manage');
    }
  } catch (error) {
    showToast('加载文档失败');
  } finally {
    loading.value = false;
  }
};

const loadVersions = async () => {
  try {
    const versions = await docStore.fetchDocumentVersions(docId.value);
    documentVersions.value = versions;
  } catch (error) {
    console.error('加载版本失败', error);
  }
};

const toggleEdit = async () => {
  if (isEditing.value) {
    // 取消编辑，恢复内容
    if (editorRef.value) {
      editorRef.value.innerHTML = document.doc_content || '';
    }
    isEditing.value = false;
  } else {
    // 开始编辑前检查文档锁定状态
    if (document.edit_status === 1 && document.last_editor_uid !== currentUserId.value) {
      showToast('文档正在被其他用户编辑');
      return;
    }
    
    // 尝试锁定文档
    try {
      await docStore.lockDocument(docId.value);
      document.edit_status = 1;
      isEditing.value = true;
      await nextTick();
      // 聚焦编辑器
      if (editorRef.value) {
        editorRef.value.focus();
      }
    } catch (error) {
      showToast('获取编辑权限失败');
    }
  }
};

const formatText = (command: string, value?: string) => {
  document.execCommand(command, false, value);
  if (editorRef.value) {
    editorRef.value.focus();
  }
};

const handleContentChange = () => {
  if (editorRef.value) {
    document.doc_content = editorRef.value.innerHTML;
  }
};

const updateTitle = async () => {
  if (!canEdit.value) return;
  
  try {
    await docStore.updateDocument(docId.value, {
      doc_title: document.doc_title
    });
  } catch (error) {
    showToast('更新标题失败');
  }
};

const saveDocument = () => {
  // 显示编辑备注弹窗
  showEditNote.value = true;
};

const confirmSaveWithNote = async () => {
  saving.value = true;
  try {
    await docStore.updateDocument(docId.value, {
      doc_content: document.doc_content,
      edit_note: editNote.value
    });
    
    // 重新获取文档信息
    const updatedDoc = await docStore.fetchDocumentDetail(docId.value);
    if (updatedDoc) {
      Object.assign(document, updatedDoc);
    }
    
    // 重新加载版本
    await loadVersions();
    
    showToast('保存成功');
    isEditing.value = false;
    showEditNote.value = false;
    editNote.value = '';
  } catch (error) {
    showToast('保存失败');
  } finally {
    saving.value = false;
  }
};

const selectVersion = (version: DocumentVersion) => {
  selectedVersion.value = version;
  showVersionDetail.value = true;
};

const restoreVersion = async () => {
  if (!selectedVersion.value) return;
  
  try {
    await docStore.restoreDocumentVersion(docId.value, selectedVersion.value.id);
    
    // 重新加载文档
    await loadDocument();
    showToast('恢复版本成功');
    showVersionDetail.value = false;
  } catch (error) {
    showToast('恢复版本失败');
  }
};

const handleMoreAction = async (action: any) => {
  showMoreMenu.value = false;
  
  if (action.value === 'delete') {
    // 确认删除
    if (confirm('确定要删除此文档吗？')) {
      try {
        await docStore.deleteDocument(docId.value);
        showToast('删除成功');
        router.push('/document/manage');
      } catch (error) {
        showToast('删除失败');
      }
    }
  } else if (action.value === 'permission') {
    // 修改权限功能待实现
    showToast('功能开发中');
  }
};

const goBack = () => {
  router.back();
};

// 组件卸载时解锁文档
const cleanup = async () => {
  if (document.edit_status === 1 && currentUserId.value === document.last_editor_uid) {
    try {
      await docStore.unlockDocument(docId.value);
    } catch (error) {
      console.error('解锁文档失败', error);
    }
  }
};

// 监听页面关闭或刷新
const setupBeforeUnload = () => {
  window.addEventListener('beforeunload', cleanup);
  return () => {
    window.removeEventListener('beforeunload', cleanup);
  };
};

// 初始化
onMounted(async () => {
  const user = await userStoreAPI.getCurrentUser();
  if (!user) {
    showToast('请先登录');
    router.push('/login');
    return;
  }
  await loadDocument();
  setupBeforeUnload();
});
</script>

<style scoped>
.document-detail-container {
  min-height: 100vh;
  background-color: #fff;
  position: relative;
}

.top-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 10;
}

.document-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.document-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  border: none;
  outline: none;
  width: 100%;
  padding: 8px 0;
  margin-bottom: 12px;
}

.document-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  font-size: 12px;
  color: #999;
}

.document-type {
  background-color: #f0f9ff;
  color: #1989fa;
  padding: 2px 8px;
  border-radius: 3px;
}

.editor-toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px 16px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e8e8e8;
  position: sticky;
  top: 50px;
  z-index: 10;
}

.tool-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.tool-group .van-icon {
  cursor: pointer;
  color: #666;
}

.tool-group .van-icon:active {
  color: #1989fa;
}

.document-content-container {
  min-height: 500px;
}

.editor-container {
  padding: 16px;
}

.rich-editor {
  min-height: 400px;
  line-height: 1.8;
  font-size: 15px;
  color: #333;
  outline: none;
}

.rich-editor:empty:before {
  content: attr(data-placeholder);
  color: #999;
  pointer-events: none;
}

.preview-container {
  padding: 16px;
  line-height: 1.8;
  font-size: 15px;
  color: #333;
}

.preview-container h1,
.preview-container h2,
.preview-container h3 {
  margin: 16px 0 10px 0;
}

.preview-container p {
  margin: 10px 0;
}

.preview-container ul,
.preview-container ol {
  margin: 10px 0;
  padding-left: 24px;
}

.bottom-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
  position: sticky;
  bottom: 0;
  background-color: #fff;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

/* 版本面板样式 */
.version-panel,
.version-detail-panel,
.edit-note-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.panel-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.version-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 16px;
}

.version-item {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.version-info {
  flex: 1;
}

.version-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.version-number {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.current-version {
  font-size: 12px;
  color: #1989fa;
}

.version-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.version-note {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.version-detail-info {
  padding: 16px;
  background-color: #f5f5f5;
  font-size: 13px;
  color: #666;
  line-height: 1.6;
}

.version-detail-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  line-height: 1.6;
  font-size: 14px;
  color: #333;
}

.panel-footer {
  display: flex;
  gap: 10px;
  padding: 16px;
  border-top: 1px solid #f0f0f0;
}

.panel-footer .van-button {
  flex: 1;
}

.note-input {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.note-input textarea {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 10px;
  font-size: 14px;
  resize: none;
  flex: 1;
}

.note-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}
</style>